using System.IO;

namespace SMS.SMPPClient.Common
{
    public class PushMessage
    {
        // Fields
        private ServiceIndication serviceIndication;
        protected static byte[] WDP_DESTINATIONPORT = new byte[] { 11, 0x84 };
        protected static byte[] WDP_SOURCEPORT = new byte[] { 0x23, 240 };

        // Methods
        public PushMessage(string href, string text)
        {
            this.serviceIndication = new ServiceIndication(href, text, ServiceIndicationAction.signal_high);
        }

        public byte[] GetPDUBytes()
        {
            byte[] wBXMLBytes = this.serviceIndication.GetWBXMLBytes();
            byte[] wSPHeaderBytes = this.GetWSPHeaderBytes((byte)wBXMLBytes.Length);
            MemoryStream stream1 = new MemoryStream();
            stream1.Write(wSPHeaderBytes, 0, wSPHeaderBytes.Length);
            stream1.Write(wBXMLBytes, 0, wBXMLBytes.Length);
            return stream1.ToArray();
        }

        public byte[] GetSMSBytes()
        {
            MemoryStream stream1 = new MemoryStream();
            byte[] wDPHeaderBytes = this.GetWDPHeaderBytes();
            stream1.Write(wDPHeaderBytes, 0, wDPHeaderBytes.Length);
            byte[] pDUBytes = this.GetPDUBytes();
            stream1.Write(pDUBytes, 0, pDUBytes.Length);
            return stream1.ToArray();
        }

        public byte[] GetWDPHeaderBytes()
        {
            MemoryStream stream1 = new MemoryStream();
            stream1.WriteByte(5);
            stream1.WriteByte((byte)(WDP_DESTINATIONPORT.Length + WDP_SOURCEPORT.Length));
            stream1.Write(WDP_DESTINATIONPORT, 0, WDP_DESTINATIONPORT.Length);
            stream1.Write(WDP_SOURCEPORT, 0, WDP_SOURCEPORT.Length);
            
            MemoryStream stream2 = new MemoryStream();
            stream2.WriteByte((byte)stream1.Length);
            stream1.WriteTo(stream2);
            return stream2.ToArray();
        }

        public byte[] GetWSPHeaderBytes(byte contentLength)
        {
            MemoryStream stream1 = new MemoryStream();
            stream1.WriteByte(0x25);
            stream1.WriteByte(6);
            
            MemoryStream stream2 = new MemoryStream();
            stream2.Write(WSP.HEADER_CONTENTTYPE_application_vnd_wap_sic_utf_8, 0, WSP.HEADER_CONTENTTYPE_application_vnd_wap_sic_utf_8.Length);
            stream2.WriteByte(0xaf);
            stream2.WriteByte(130);
            stream2.Write(WSP.HEADER_PUSHFLAG, 0, WSP.HEADER_PUSHFLAG.Length);
            stream1.WriteByte((byte)stream2.Length);
            stream2.WriteTo(stream1);
            
            return stream1.ToArray();
        }
    }
}

